//
//  FlyHomeViewController.m
//  JiongTu
//
//  Created by Dupengfei on 16/3/12.
//  Copyright © 2016年 YSKJ. All rights reserved.
//

#define TRIP_LOC [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"homeTrip.archive"]

#import "ControllerManger.h"
#import "FlyHomeViewController.h"
#import "FlyHomeTableViewCell.h"
#import "FlyScrollView.h"
#import "FlyFindCarViewController.h"
#import "PublishCarViewController.h"
#import "PersonalMessageViewController.h"
#import "MJRefresh.h"
#import "JTConst.h"
#import "UIView+Extension.h"
#import "LoginViewController.h"
#import "JTPassengerTrip.h"
#import "JTDriverTrip.h"
#import <AVCloud.h>
#import <AVOSCloud.h>
#import <SVProgressHUD.h>

@interface FlyHomeViewController ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong)FlyScrollView * scrollView;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong)NSMutableArray * array;

@property (nonatomic, strong)UIButton * findCarButton;

@property (nonatomic, strong)UIButton * pushCarButton;

@property (nonatomic, strong)UIBarButtonItem * leftButton;

@property (nonatomic, assign) NSInteger countNumber;

@property (weak, nonatomic) IBOutlet UIView *headView;

/**
 *  按钮是否隐藏
 */
@property (nonatomic, assign) BOOL isHidden;

@property (nonatomic, strong) NSMutableArray * driverArray;

@property (nonatomic, assign) NSInteger driverCount;


@end

@implementation FlyHomeViewController {
    NSArray *_homeTrips;
}
/**
 *  记录TableView滚动的位置
 */
int _lastPosition;

- (NSMutableArray *)array {
    if (!_array) {
        _array = [NSMutableArray array];
    }
    return _array;
}

- (NSMutableArray *)driverArray {
    if (!_driverArray) {
        _driverArray = [NSMutableArray array];
    }
    return _driverArray;
}

- (NSArray *)homeTrips {
    if (!_homeTrips) {
        _homeTrips = [NSArray array];
    }
    return _homeTrips;
}

- (void)setHomeTrips:(NSArray *)homeTrips {
    _homeTrips = homeTrips;
   }
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeInterface];
    _countNumber = 0;
    _driverCount =0;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
                    _countNumber =0+(int)_array.count;
                     _driverCount = 0+(int)_driverArray.count;
        [self initializeDateSource];
    }];
    [self.tableView.mj_header beginRefreshing];
}
-(void)initializeDateSource
{
//    [self.array removeAllObjects];
//    
//    [self.driverArray removeAllObjects];
    
    NSDate * date =[NSDate date];
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat=@"yyyy年MM月dd日";
    NSString *timeStr=[formatter stringFromDate:date];
     
    
        [AVCloud callFunctionInBackground:@"homeOrder" withParameters:@{@"time":timeStr,@"skip":@(_countNumber),@"limit":@(3)} block:^(id object, NSError *error) {
            if (object) {
                
                NSRange range =NSMakeRange(0, [JTPassengerTrip tripWithAVObjects:object].count);
                
                NSIndexSet * indexSet =[NSIndexSet indexSetWithIndexesInRange:range];
            
                 [self.array insertObjects:[JTPassengerTrip tripWithAVObjects:object] atIndexes:indexSet];
                [AVCloud callFunctionInBackground:@"homeSearch" withParameters:@{@"driverDate":timeStr,@"skip":@(_driverCount),@"limit":@(3)} block:^(id object, NSError *error) {
                    
                    NSRange range1 =NSMakeRange(0, [JTDriverTrip tripWithAVObjects:object].count);
                    NSIndexSet * indexSet1 =[NSIndexSet indexSetWithIndexesInRange:range1];
                    [self.driverArray insertObjects:[JTDriverTrip tripWithAVObjects:object] atIndexes:indexSet1];
                    self.homeTrips = [self.array arrayByAddingObjectsFromArray:self.driverArray];
//                    [self.tableView.mj_footer endRefreshing];
                    [self.tableView.mj_header endRefreshing];
                    [self.tableView reloadData];
                    
                    _driverCount =self.driverArray.count;
                    
                    _countNumber =self.array.count;
                    
                }];
            }
            if (error) {
               [SVProgressHUD showErrorWithStatus:error.localizedDescription];
            }
//            NSLog(@"%d",_countNumber);
//            
//            NSLog(@"%d",_driverCount);
            
            
        }];
    
    AVQuery * driverQuery = [AVQuery queryWithClassName:@"DriverTrip"];
    [driverQuery whereKey:@"Date" greaterThanOrEqualTo:timeStr];
    [driverQuery orderByDescending:@"createdAt"];
}

-(void)initializeInterface
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.leftBarButtonItem = self.leftButton;
    
    self.navigationItem.title = @"首页";
    
    _tableView.delegate = self;
    
    _tableView.dataSource =self;
}


-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    [self.headView addSubview:self.scrollView];
    
    [self.view addSubview:self.findCarButton];
    
    [self.view addSubview:self.pushCarButton];
    
}
#pragma mark - delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.homeTrips.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (self.homeTrips.count) {
        FlyHomeTableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:@"homeCell"];
        
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"FlyHomeTableViewCell" owner:nil options:nil] lastObject];
        }
        cell.tripObject = self.homeTrips[indexPath.row];
        
        
        return cell;
//    } else {
//        
//    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 95;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - ScrollView代理
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    int currentPostion = scrollView.contentOffset.y;
       
    if (currentPostion == 0) {
        [self animateButton:NO];
    } else if (currentPostion - _lastPosition > 40) {
        _lastPosition = currentPostion;
        [self animateButton:YES];
    } else if (_lastPosition - currentPostion > 40) {
        _lastPosition = currentPostion;
        [self animateButton:NO];
    }
    
    
}

#pragma mark 按键弹出收起动画
- (void)animateButton:(BOOL)up {
    //正在上滑
    if (up) {
        self.isHidden = YES;
        [UIView animateWithDuration:0.5 animations:^{
            self.findCarButton.frame = CGRectMake(self.view.frame.size.width*0.168, self.view.frame.size.height, self.view.frame.size.width*0.2427, self.view.frame.size.width*0.2427);
            self.pushCarButton.frame = CGRectMake(self.view.frame.size.width*0.5893, self.view.frame.size.height, self.view.frame.size.width*0.2427, self.view.frame.size.width*0.2427);
        }];
        //正在下滑
    } else if (!up) {
        if (self.isHidden == YES) {
            [UIView animateWithDuration:0.5 animations:^{
                self.findCarButton.frame = CGRectMake(self.view.frame.size.width*0.168, self.view.frame.size.height-self.view.frame.size.width*0.2427-15, self.view.frame.size.width*0.2427, self.view.frame.size.width*0.2427);
                self.pushCarButton.frame = CGRectMake(self.view.frame.size.width*0.5893, self.view.frame.size.height-self.view.frame.size.width*0.2427-15, self.view.frame.size.width*0.2427, self.view.frame.size.width*0.2427);
            }];
            self.isHidden = NO;
        }
    }
}

#pragma mark - getter
-(FlyScrollView *)scrollView
{
    if (_scrollView ==nil) {
        //取消自动设置Inset
        self.automaticallyAdjustsScrollViewInsets = NO;
        //水平方向的滚动
        _scrollView = [[FlyScrollView alloc] init];
        //尺寸
        _scrollView.frame =_headView.frame;
        //图片切换时间
        _scrollView.time = 5;
        //图片数组
        
        _scrollView.images = @[
                               [UIImage imageNamed:@"首页banner"],
                               [UIImage imageNamed:@"首页banner2"],
                               [UIImage imageNamed:@"首页banner3"]
                               ];
    }
    return _scrollView;
}

-(UIButton *)findCarButton
{
    if (!_findCarButton) {
        
        _findCarButton = [[UIButton alloc]init];
        
        _findCarButton.frame = CGRectMake(self.view.frame.size.width*0.168, self.view.frame.size.height-self.view.frame.size.width*0.2427-15, self.view.frame.size.width*0.2427, self.view.frame.size.width*0.2427);
        
        [_findCarButton setBackgroundImage:[UIImage imageNamed:@"主页3_14"] forState:UIControlStateNormal];
        
        [_findCarButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
        
        _findCarButton.tag =201;
        
    }
    return _findCarButton;
}

-(UIButton *)pushCarButton
{
    if (!_pushCarButton) {
        
        _pushCarButton = [[UIButton alloc]init];
        
        _pushCarButton.frame = CGRectMake(self.view.frame.size.width*0.5893, self.view.frame.size.height-self.view.frame.size.width*0.2427-15, self.view.frame.size.width*0.2427, self.view.frame.size.width*0.2427);
        
        [_pushCarButton setBackgroundImage:[UIImage imageNamed:@"主页3_11"] forState:UIControlStateNormal];
        
        [_pushCarButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
        
        
        _pushCarButton.tag =202;
    }
    return _pushCarButton;
}

-(UIBarButtonItem *)leftButton
{
    if (!_leftButton) {
        
        _leftButton =[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"主页43_06"] style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonPressed:)];
        
        
    }
    return _leftButton;
    
}


-(void)buttonPressed:(UIButton *)sender
{
    UIStoryboard * story =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    
    if (![AVUser currentUser]) {
        
        LoginViewController *lgVC = [story instantiateViewControllerWithIdentifier:@"login"];
        
//        [self presentViewController:lgVC animated:YES completion:nil];
        [self.navigationController pushViewController:lgVC animated:YES];
        
        return;
    }
    
    else{
    
    switch (sender.tag-200) {
        case 1:
        {
            FlyFindCarViewController * view =[[FlyFindCarViewController alloc]init];
            [self.navigationController pushViewController:view animated:YES];
        }
            break;
        case 2:
        {
            if ([[AVUser currentUser][@"DriverAudit"]intValue]==0)
            {
                UIAlertController * alertVC =[UIAlertController alertControllerWithTitle:@"提示" message:@"您还没有实名认证，请前往个人中心进行实名、实车认证" preferredStyle: UIAlertControllerStyleAlert];
                UIAlertAction * action =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    PersonalMessageViewController * view = [[PersonalMessageViewController alloc]init];
                    [self.navigationController pushViewController:view animated:YES];
                }];
                UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                }];
                
                [alertVC addAction:action1];
                
                [alertVC addAction:action];
                
                [self presentViewController:alertVC animated:YES completion:nil];
            }
            else{
            
            PublishCarViewController *pubVC = [story instantiateViewControllerWithIdentifier:@"pub"];
            [self.navigationController pushViewController:pubVC animated:YES];
            }
        }
            break;
            
        default:
            break;
    }
    }
    
}

-(void)leftButtonPressed:(UIBarButtonItem *)sender
{
    [[ControllerManger sharedManager].drawerVC openLeftDrawer];
}



@end
